using System;
using System.IO;
using System.Xml.Serialization;
using IDeal.Models;

namespace IDeal.Services
{
    public class FileBasedIssuersStorage : IIssuersStorage
    {
        private readonly string _path;

        public FileBasedIssuersStorage(string path)
        {
            _path = path;
        }

        public void Save(IssuersDirectory issuers)
        {
            using (var fileStream = File.Open(_path, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                var serializer = new XmlSerializer(typeof(IssuersDirectory));
                serializer.Serialize(fileStream, issuers);
                fileStream.Flush();
                fileStream.Close();
            }
        }

        public IssuersDirectory Load()
        {
            if(!File.Exists(_path))
                return IssuersDirectory.Empty;

            try
            {
                using (var fileStream = File.Open(_path, FileMode.Open))
                {
                    var serializer = new XmlSerializer(typeof (IssuersDirectory));
                    var issuers = (IssuersDirectory)serializer.Deserialize(fileStream);

                    fileStream.Close();
                    return issuers;
                }
            }
            catch (Exception)
            {
                return IssuersDirectory.Empty;
            }
            
        }
    }
}